<template>
  <div
    ref="codeEditorContent"
    class="code-container"
    id="codeEditorContent"
  ></div>
</template>

<script setup>
import { onMounted, ref, toRaw } from "vue";
import * as monacoEditor from "monaco-editor";

const props = defineProps({
  codes: {
    type: String,
    default: ""
  },
  editorConfig: {
    type: Object,
    default: () => {
      return {
        // model: null,
        value: "", //编辑器初始显示文字
        language: "javascript", //语言支持
        theme: "vs-dark", // 官方自带三种主题 vs, hc-black, or vs-dark
        selectOnLineNumbers: true, //显示行号
        roundedSelection: false,
        readOnly: false, // 只读
        cursorStyle: "line", //光标样式
        glyphMargin: true, //字形边缘
        useTabStops: true,
        fontSize: 14, //字体大小
        autoIndent: "full", //自动布局
        quickSuggestionsDelay: 100, //代码提示延时
        automaticLayout: true //自适应,
      };
    }
  }
});

const editorDefaultConfig = ref({
  value: "", //编辑器初始显示文字
  language: "javascript", //语言支持
  theme: "vs", // 官方自带三种主题 vs, hc-black, or vs-dark
  selectOnLineNumbers: true, //显示行号
  roundedSelection: false,
  readOnly: false, // 只读
  cursorStyle: "line", //光标样式
  glyphMargin: true, //字形边缘
  useTabStops: true,
  fontSize: 14, //字体大小
  autoIndent: "full", //自动布局
  quickSuggestionsDelay: 100, //代码提示延时
  automaticLayout: true //自适应,
});
const emits = defineEmits([]);

const editorValue = ref("");
const editorInstance = ref();

const initEditor = () => {
  const dom = document.getElementById("codeEditorContent");
  if (!dom) return;
  // 初始化编辑器，确保dom已经渲染
  editorInstance.value = monacoEditor.editor.create(
    dom,
    Object.assign({}, editorDefaultConfig.value, {
      ...props.editorConfig,
      value: props.codes
    })
  );
  // 监听值的变化
  // @ts-ignore
  editorInstance.value.onDidChangeModelContent((event) => {
    editorValue.value = getEditorValue();
  });
};

// 获取编辑器中的文本
const getEditorValue = () => {
  if (!editorInstance.value) return "";
  const val = toRaw(editorInstance?.value).getValue();
  return val || "";
};

onMounted(() => {
  initEditor();
});
</script>

<style scoped lang="scss">
</style>
